<?php
/**
 * Created by PhpStorm.
 * User: au
 * Date: 18-5-24
 * Time: 上午12:55
 */

namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Events\RepositoryEntityUpdated;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

abstract class CommonRepository extends BaseRepository
{
    /**
     * 通过字段查找一条记录
     * @param       $field
     * @param       $value
     * @param array $columns
     * @return mixed
     */
    public function findOneByField($field, $value = null, $columns = ['*'])
    {
        $model = $this->findWhere([$field => $value], $columns)->first();

        return $model;
    }

    /**
     * 根据指定字段删除
     *
     * @param $field
     * @param $value
     * @return int
     */
    public function deleteByField($field, $value)
    {
        return $this->deleteWhere([$field => $value]);
    }

    /**
     * 是否在允许的枚举值内
     *
     * @param $needle
     * @param array $enum
     */
    protected function isIn($needle, array $enum)
    {
        if (!in_array($needle, $enum)) {
            throw new BadRequestHttpException();
        }
    }

    /**
     * 更新指定字段
     * 这些字段都是受更新限制的字段（只能由某个角色操作）
     * 也即这些字段不会出现在模型的 fillable 属性上
     * 即不可批量赋值的字段
     *
     * @param array $attr
     * @param $id
     * @return mixed
     */
    public function updateFields(array $attr, $id)
    {
        $model = $this->model->findOrFail($id);

        foreach ($attr as $key => $value) {
            $model->setAttribute($key, $value);
        }

        $model->save();

        $this->resetModel();

        event(new RepositoryEntityUpdated($this, $model));

        return $this->parserResult($model);
    }

    /**
     * 状态反转
     *
     * @param $field
     * @param $id
     * @return mixed
     */
    public function reverseStatus($field, $id)
    {
        $model = $this->find($id, [$field]);

        //取反
        $reverse = ~intval($model->getAttributeValue($field)) & 1;

        $model->setAttribute($field, $reverse);

        return $model->save();
    }

    /**
     * 生成唯一的用户id
     *
     * @param int $length
     * @return string
     */
    protected function generateId($length = 20)
    {
        do {
            $id = randString($length);
        } while ($this->model->find($id, ['id']));      // no fail

        return $id;
    }
}